<template>
  <el-icon :size="size2Number" :class="[props.class,props.type]"
           :color="props.color" v-if="which" :style="xhStyle">
    <component :is="iconName"></component>
  </el-icon>
  <span v-else :class="[props.class,props.type]" :style="xhStyle"></span>
</template>

<script setup>
import {computed, watch, ref} from 'vue'
import { ElIcon } from 'element-plus'
import * as Icons from '@element-plus/icons-vue' // 【步骤1】全量引入svg图标
import 'element-plus/es/components/icon/style/css'

const props = defineProps({
  // 图标前缀
  class: {
    type: String,
    default: 'xhAll'
  },
  size: { // 图标尺寸
    type: [Number, String],
    default: 14
  },
  color: { // 图标颜色
    type: String,
    default: 'inherit'
  },
  type: { // 图标类型
    type: String,
    default: ''
  },
  styleX: {
    type: [Object, String],
    default: {width: 'auto'}
  }
})

// 如果是自定义类名
const xhStyle = computed(() => {
  if (typeof props.styleX != 'string') {
    return props.style
  } else if (typeof props.styleX == 'string') {
    const result = {}
    // width: 100px;
    const oneList = props.styleX.split(';')
    oneList.forEach(item => {
      const twoList = item.split(':') || []
      if (twoList.length >= 2) {
        result[twoList[0]] = twoList[1]
      }
      ;
    })
    return result
  }
})

// 【步骤4】size转换成数值型
const size2Number = computed(() => {
  if (isNaN(props.size)) {
    return 20
  }
  return Number(props.size)
})

// 【步骤6】动态获取图标
const iconName = computed(() => {
  let iconType = props.type
  let icon = null

  if (iconType !== '') {
    // 【步骤5】首字母大写
    icon = iconType.replace(iconType[0], iconType[0].toUpperCase())
  }
  // console.log('iconX',icon)
  return Icons[icon] // 通过中括号的方式动态获取
  // return icon // 通过中括号的方式动态获取
})


const which = ref(true) // 默认为element图标
watch(() => props.type, newV => {
  which.value = newV.indexOf(props.class) != -1 ? false : true // 找到前缀则代表用自己的字体
}, {immediate: true})
</script>

<style scoped lang='scss'>

</style>